
package com.shiku.imserver.common.utils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HttpParseUtils {
    private static ConcurrentHashMap<Integer, Pattern> regexPattern = new ConcurrentHashMap<>();


    private static Pattern getCachedPattern(String regex) {

        Pattern pattern = null;

        if (regexPattern.containsKey(Integer.valueOf(regex.hashCode()))) {

            pattern = regexPattern.get(Integer.valueOf(regex.hashCode()));

        } else {

            pattern = Pattern.compile(regex);

            regexPattern.put(Integer.valueOf(regex.hashCode()), pattern);

        }

        return pattern;

    }


    public static Map<String, String> getEqualMap(String str) {

        Map<String, String> equalMap = new HashMap<>();

        String[] searchedStrings = searchByRegex(str, "([^ ;,]+=[^ ;,]+)");

        for (String groupString : searchedStrings) {


            String[] equalStrings = new String[2];

            int equalCharIndex = groupString.indexOf("=");

            equalStrings[0] = groupString.substring(0, equalCharIndex);

            equalStrings[1] = groupString.substring(equalCharIndex + 1, groupString.length());

            if (equalStrings.length == 2) {

                String key = equalStrings[0];

                String value = equalStrings[1];

                if (value.startsWith("\"") && value.endsWith("\"")) {

                    value = value.substring(1, value.length() - 1);

                }

                equalMap.put(key, value);

            }

        }

        return equalMap;

    }


    public static String getPerprotyEqualValue(Map<String, String> packetMap, String propertyName, String valueName) {

        String propertyValueObj = packetMap.get(propertyName);

        if (propertyValueObj == null) {

            return null;

        }

        String propertyValue = propertyValueObj.toString();

        Map<String, String> equalMap = getEqualMap(propertyValue);

        return equalMap.get(valueName);

    }


    public static void main(String[] args) {
    }


    public static String[] searchByRegex(String source, String regex) {

        if (source == null) {

            return null;

        }


        Pattern pattern = getCachedPattern(regex);

        Matcher matcher = pattern.matcher(source);

        ArrayList<String> result = new ArrayList<>();

        while (matcher.find()) {

            result.add(matcher.group());

        }

        return result.<String>toArray(new String[0]);

    }

}


